<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>视频在线人数统计</title>
    <style>
        body { font-family: sans-serif; text-align: center; padding-top: 50px; background-color: #f0f2f5; }
        .counter { font-size: 48px; font-weight: bold; color: #333; margin: 20px 0; }
        .video-id { color: #666; }
    </style>
</head>
<body>
<h1>视频在线人数实时统计</h1>
<p class="video-id">当前视频ID: <span id="currentVideoId">video-123</span></p>
<div class="counter">
    当前在线: <span id="onlineCount">0</span> 人
</div>

<script>
    // 视频ID，你可以从URL或页面其他地方获取
    const videoId = "video-123";
    // WebSocket连接地址
    const wsUri = `ws://localhost:8080/ws/video?videoId=${videoId}`;

    let websocket = null;

    function initWebSocket() {
        console.log(`正在连接到 WebSocket 服务器: ${wsUri}`);
        websocket = new WebSocket(wsUri);

        websocket.onopen = function(evt) {
            console.log("连接成功！");
        };

        websocket.onmessage = function(evt) {
            console.log("收到消息: " + evt.data);
            try {
                const message = JSON.parse(evt.data);
                // 更新页面上的在线人数
                if (message.type === 'COUNT_UPDATE') {
                    document.getElementById('onlineCount').textContent = message.count;
                }
            } catch (e) {
                console.error("解析服务器消息失败: " + e);
            }
        };

        websocket.onerror = function(evt) {
            console.error("WebSocket 错误: ", evt);
        };

        websocket.onclose = function(evt) {
            console.log("连接关闭，正在尝试重连...");
            // 实现自动重连
            setTimeout(initWebSocket, 3000);
        };
    }

    // 页面加载时初始化WebSocket连接
    window.addEventListener('load', initWebSocket);

    // 页面关闭时，尝试优雅地关闭连接
    window.addEventListener('beforeunload', function() {
        if (websocket && websocket.readyState === WebSocket.OPEN) {
            websocket.close();
        }
    });
</script>
</body>
</html>